<template>
  <div class="chat-container">
    <div class="chat-header">
      <h1>DeepSeek 交互界面</h1>
      <button @click="confirmClear()" class="clear-button">清除聊天</button>
    </div>
    <div class="chat-messages" ref="messagesContainer">
      <div v-for="(message, index) in messages" :key="index" class="message-wrapper">
        <div :class="['message', message.role === 'user' ? 'user-message' : 'ai-message']">
          <div class="message-avatar">{{ message.role === 'user' ? 'U' : 'AI' }}</div>
          <div class="message-content">
          {{ message.content }}
          <div class="message-timestamp">{{ message.timestamp.toLocaleTimeString() }}</div>
          <div v-if="message.role === 'user' && message.status === 'sending'" class="message-status sending">
            <div class="status-dot"></div>
          </div>
          <div v-if="message.role === 'user' && message.status === 'failed'" class="message-status failed">
            ⚠️ 发送失败
          </div>
        </div>
        </div>
      </div>
      <div v-if="isLoading" class="loading-indicator">
        <div class="loading-dot"></div>
        <div class="loading-dot"></div>
        <div class="loading-dot"></div>
      </div>
    </div>
    <div class="chat-input-area">
      <textarea
        v-model="currentMessage"
        @keydown.enter="handleEnter"
        placeholder="输入消息...按Shift+Enter换行，Enter发送"
        class="message-input"
      ></textarea>
      <button @click="sendMessage" class="send-button">发送</button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, watch } from 'vue';
import { useChatStore } from '../store/chat';

type Message = {
  role: 'user' | 'assistant';
  content: string;
  timestamp: Date;
};

const chatStore = useChatStore();
const currentMessage = ref('');
const messagesContainer = ref<HTMLDivElement | null>(null);
const isLoading = ref(false);

const { messages } = chatStore;

watch(messages, () => scrollToBottom());

onMounted(scrollToBottom);

function scrollToBottom() {
  if (messagesContainer.value) {
    messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
  }
}

function confirmClear() {
  if (confirm('确定要清除所有聊天记录吗？')) {
    chatStore.clearMessages();
  }
}

function handleEnter(e: KeyboardEvent) {
  if (e.shiftKey) {
    // 允许Shift+Enter换行
    const start = (e.target as HTMLTextAreaElement).selectionStart;
    const end = (e.target as HTMLTextAreaElement).selectionEnd;
    currentMessage.value = currentMessage.value.substring(0, start) + '\n' + currentMessage.value.substring(end);
    // 调整光标位置
    setTimeout(() => {
      (e.target as HTMLTextAreaElement).selectionStart = (e.target as HTMLTextAreaElement).selectionEnd = start + 1;
    }, 0);
  } else {
    // 普通Enter发送消息
    sendMessage();
  }
}

async function getAIResponse(message: string): Promise<string> {
  try {
      console.log('Sending request to /api/chat/completions with body:', {
        messages: [{ role: 'user', content: message }],
        model: 'deepseek-chat',
        stream: false
      });
      const response = await request<{
      data: {
        content: string
      }
    }>('/api/chat/completions', {
      method: 'POST',
      body: JSON.stringify({
          messages: [{
            role: 'user',
            content: message
          }],
          model: 'deepseek-chat',
          stream: false
        })
    });
    return response.data.content;
  } catch (error) {
    console.error('AI请求失败:', error);
    throw new Error('获取AI响应失败，请稍后重试');
  }
}

async function sendMessage() {
  const userMessage = currentMessage.value.trim();
  if (!userMessage) return;

  // 添加消息发送状态
  const messageId = Date.now().toString();
  chatStore.addMessage({
    role: 'user', 
    content: userMessage, 
    timestamp: new Date(),
    status: 'sending'
  });
  currentMessage.value = '';
  isLoading.value = true;

  try {
    // 模拟AI响应，实际项目中替换为真实API调用
    const aiResponse = await getAIResponse(userMessage);
    chatStore.addMessage({ role: 'assistant', content: aiResponse, timestamp: new Date() });
  } catch (error) {
    chatStore.addMessage({
      role: 'assistant',
      content: '抱歉，处理请求时出错，请重试。',
      timestamp: new Date()
    });
  } finally {
    isLoading.value = false;
  }
}

import { request } from '@/api/request';

</script>

<style scoped>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  overflow: hidden;
}

@media (max-width: 768px) {
  .chat-container {
    max-width: 100%;
    border-radius: 0;
    border: none;
  }

  .message {
    max-width: 85%;
  }
}

.chat-header {
  background-color: #0078ff;
  color: white;
  padding: 1rem;
  text-align: center;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.chat-messages {
  flex: 1;
  padding: 1rem;
  overflow-y: auto;
  background-color: #f9f9f9;
}

.message-wrapper {
  margin-bottom: 1rem;
}

.message {
  display: flex;
  max-width: 70%;
}

.user-message {
  margin-left: auto;
  flex-direction: row-reverse;
}

.ai-message {
  margin-right: auto;
}

.message-avatar {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background-color: #0078ff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  margin: 0 0.5rem;
}

.user-message .message-avatar {
  background-color: #42b883;
}

.message-content {
  padding: 0.8rem 1.2rem;
  border-radius: 18px;
  background-color: white;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.1);
}

.message-timestamp {
  font-size: 12px;
  color: #999;
  margin-top: 4px;
  text-align: right;
}

.message-status {
  font-size: 12px;
  margin-top: 4px;
  text-align: right;
}

.sending .status-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #0078ff;
  display: inline-block;
  animation: pulse 1.5s infinite;
}

.failed {
  color: #ff4d4f;
}

@keyframes pulse {
  0% { opacity: 0.6; }
  50% { opacity: 1; }
  100% { opacity: 0.6; }
}

.user-message .message-content {
  background-color: #0078ff;
  color: white;
}

.chat-input-area {
  display: flex;
  padding: 1rem;
  border-top: 1px solid #e0e0e0;
}

.message-input {
  flex: 1;
  padding: 0.8rem 1.2rem;
  border: 1px solid #e0e0e0;
  border-radius: 24px;
  resize: none;
  outline: none;
  font-size: 14px;
  min-height: 48px;
  max-height: 120px;
}

.send-button {
  margin-left: 0.8rem;
  padding: 0.8rem 1.6rem;
  background-color: #0078ff;
  color: white;
  border: none;
  border-radius: 24px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.send-button:hover {
  background-color: #0056b3;
}

.clear-button {
  margin-left: 0.8rem;
  padding: 0.5rem 1rem;
  background-color: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s;
}

.clear-button:hover {
  background-color: #e0e0e0;
}

.loading-indicator {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  padding: 0.8rem 1.2rem;
}

.loading-dot {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #999;
  margin: 0 3px;
  animation: loading 1.4s infinite ease-in-out both;
}

.loading-dot:nth-child(1) {
  animation-delay: -0.32s;
}

.loading-dot:nth-child(2) {
  animation-delay: -0.16s;
}

@keyframes loading {
  0%, 80%, 100% {
    transform: scale(0);
  }
  40% {
    transform: scale(1);
  }
}
</style>